package cn.fafu.fafu_record.utils;

import cn.fafu.fafu_record.config.Exception.MyException;
import cn.fafu.fafu_record.entity.User;
import cn.fafu.fafu_record.result.ResultEnum;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.stereotype.Component;

import java.util.Date;


@Component
public class JwtUtil {

    //私钥
    public static final String SECRET_SALT = "asdfghj";
    //token过期时间
    public static final long EXPIRE_TIME = 5*60*1000;
    public static final String HEADER = "token";


    /**
     * @description 生成token
     * @param user
     * @return token 字符串
     * @date 2020年1月4日20:51:46
     */
    public static String getToken(User user) {
        String token;
        token = JWT.create()
                .withAudience(user.getUsername())                                        //包含在Token的信息
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME))       //设置过期时间
                .sign(Algorithm.HMAC256(SECRET_SALT));                                   //密钥
        return token;
    }

    /**
     * @description 验证 token
     * @param token
     * @date 2020年1月4日20:50:57
     */
    public static void verifyToken(String token){
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JwtUtil.SECRET_SALT)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new MyException(ResultEnum.EXPIRE_TOKEN_ERROR.getCode(),ResultEnum.EXPIRE_TOKEN_ERROR.getMsg());
        }
    }

    /**
     * @description 解密token 并返回 token中保存的用户名
     * @param token
     * @return
     */
    public static String decodeToken(String token){
        try {
            return JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException e){
            throw  new MyException(ResultEnum.EXPIRE_TOKEN_ERROR.getCode(),ResultEnum.EXPIRE_TOKEN_ERROR.getMsg());
        }

    }

}
